<template>
  <div class="app-content-wrap" :style="'minHeight:' + gHeight + 'px;'">
    <div class="g-content-title">
      人员管理
      <div class="department-top-btn">
        <a class="btn-default" @click="addUser()">新增人员</a>
      </div>
      <!--<router-link :to="{name: 'userModify'}"></router-link>-->
    </div>
    <!-- 搜索框 -->
    <el-form :model="userFilter" label-width="80px" size="small">
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="姓名">
            <el-col>
              <el-input v-model="userFilter.userName" placeholder="姓名"></el-input>
            </el-col>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码">
            <el-col>
              <el-input v-model="userFilter.phone" placeholder="手机号码"></el-input>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="角色" prop="role">
            <el-col>
              <SelectRole :selectModel="userFilter.role" @onRoleChange="onRoleChange"></SelectRole>
            </el-col>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="所属" prop="deptId">
            <SelectArea :selectModel="userFilter.deptId" :areaIds="areaIds" @onAreaChange="onAreaChange"></SelectArea>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="15">
        <el-form-item style="padding-left:15px;">
          <el-button type="primary" size="small" icon="el-icon-search" @click="getUserFromFilter">搜索</el-button>
        </el-form-item>
      </el-row>
    </el-form>

    <!-- 列表 -->
    <div style="margin:10px 30px;">
      <el-table :data="userListTable" border style="width: 100%">
        <el-table-column prop="userId" label="用户名" min-width="120" align="center"></el-table-column>
        <el-table-column prop="userName" label="姓名" min-width="100" align="center"></el-table-column>
        <el-table-column prop="roleName" label="角色" min-width="100" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.userRole === 1" style="color:#ff6600">{{ scope.row.roleName }}</div>
            <div v-else>{{ scope.row.roleName }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号码" min-width="140" align="center"></el-table-column>
        <el-table-column label="部门" min-width="240" align="center">
          <template slot-scope="scope">
            <div>
              {{ scope.row.deptName1 }}
              {{ scope.row.deptName2 ? "-" + scope.row.deptName2 : "" }}
              {{ scope.row.deptName3 ? "-" + scope.row.deptName3 : "" }}
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="userPhone" label="电话号码">
        </el-table-column>-->

        <!-- <el-table-column label="管理模块">
          <template slot-scope="scope">全部</template>
        </el-table-column>-->
        <el-table-column label="操作" width="190" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="userDetail(scope.row)">查看</el-button>
            <el-button type="text" @click="userModify(scope.row)">编辑</el-button>
            <el-button type="text" v-html="getStatus(scope.row.userState)" @click="lockUser(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination background @current-change="handleCurrentChange" :current-page.sync="pagination.currentPage" :page-size="10" layout="total, prev, pager, next,jumper" :total="pagination.total" class="el-page-body"></el-pagination>
    </div>
  </div>
</template>
<script>
import SelectArea from '../../components/common/select/area.vue'
import SelectRole from '../../components/common/select/role.vue'

export default {
  name: 'userList',
  data () {
    return {
      gHeight: this.$store.state.gHeight,
      selectrole: {
        role: ''
      },
      areaIds: {
        areaId1: '',
        areaId2: '',
        areaId3: ''
      },
      userFilter: {
        'userName': '', // 姓名
        'phone': '', // 电话
        'deptId': '', // 部门
        'role': '' // 角色
      },
      filterObj: {},
      userListTable: [],
      pagination: {
        currentPage: null,
        total: null
      },
      url: this.$base.getUrl('getUsers'),
      tempRoleName: ''
    }
  },
  created () {
  },
  methods: {
    addUser () {
      this.$router.push({
        name: 'userModify',
        params: {
          userId: 'addUser'
        }
      })
    },
    userDetail: function (row) {
      this.$router.push({
        name: 'userDetail',
        params: {
          userId: row.userId
        }
      })
      /*
            跳转详情页
      **/
    },
    userModify (row) {
      this.$router.push({
        name: 'userModify',
        params: {
          userId: row.userId
        }
      })
    },
    getStatus: function (status) {
      return status === '1' ? '<i class="fa fa-unlock"></i>冻结' : '<i class="fa fa-lock"></i>解冻'
    },
    _lockUser (userId, currentStates, callback) {
      let freezeUrl = this.$base.getUrl('freezeUser')
      let freeObj = {
        url: freezeUrl,
        data: {
          userId: userId,
          userState: currentStates
        }
      }
      this.$store.dispatch('postForm', freeObj).then(res => {
        if (res.code === 0) {
          callback()
        }
      })
    },
    lockUser (row) {
      /***
         冻结用户
         */
      let currStatus = row.userState
      let status
      let comStr, msgStr, canStr
      if (currStatus === '1') {
        status = 0
        comStr = '冻结后, "' + row.userName + '" 将无法登录, 是否继续?'
        msgStr = '冻结成功!'
        canStr = '已取消冻结'
      } else {
        status = 1
        comStr = '解除冻结后, "' + row.userName + '" 可正常登录, 是否继续?'
        msgStr = '解除成功!'
        canStr = '已取消解除'
      }
      this.$confirm(comStr, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _this = this
        this._lockUser(row.userId, status, function () {
          _this.getUser(_this.url, _this.filterObj)
          _this.$message({
            type: 'success',
            message: msgStr
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: canStr
        })
      })
    },
    getUserFromFilter: function () { /// /表单
      let obj = {
        'userName': this.userFilter.userName, // 姓名
        'phone': this.userFilter.phone, // 电话
        'deptId': this.userFilter.deptId, // 部门
        'role': this.userFilter.role, // 角色
        'page': 1,
        'limit': '10'
      }
      this.filterObj = obj
      let url = this.url
      this.getUser(url, obj)
      /**
         根据params获取userlist
         **/
    },
    handleCurrentChange (currPage) {
      this.filterObj.page = currPage
      let obj = this.filterObj
      let url = this.url

      this.getUser(url, obj)
    },
    getUser (url, obj) {
      this.$store.dispatch('getForm', {
        url: url,
        data: obj
      }).then((res) => {
        this.userListTable = res.list
        this.pagination.currentPage = res.currPage
        this.pagination.total = res.totalCount
      })
    },
    // role组件change时
    onRoleChange (val) {
      this.userFilter.role = val
    },
    // area组件change时
    onAreaChange (val) {
      this.userFilter.deptId = val
    }
  },
  mounted () {
    // console.log(this.$route.query.userId)
    let obj = {
      'userName': '', // 姓名
      'phone': '', // 电话
      'deptId': '', // 部门
      'role': '', // 角色
      'page': 1,
      'limit': '10'
    }
    let url = this.url
    this.getUser(url, obj)
  },
  components: {
    SelectArea,
    SelectRole
  },
  beforeRouteLeave (to, from, next) {
    if (to.name !== 'userDetail' && to.name !== 'userModify') {
      // if (to.name !== 'userDetail') {
      this.$store.commit('keepOut')
    }
    next()
  },
  beforeRouteEnter (to, from, next) {
    next((vm) => {
      let userListArr = vm.userListTable
      if (vm.$route.query.userId) {
        userListArr.forEach(item => {
          if (item.userId === vm.$route.query.userId) {
            item.userName = vm.$route.query.userName
            item.roleId = vm.$route.query.userRole
            item.mobile = vm.$route.query.mobile
            // 通过角色id获取角色名
            let params = {
              url: vm.$base.getUrl('getUserRoles')
            }
            vm.$store.dispatch('getForm', params).then((res) => {
              res.forEach(element => {
                if (element.roleId === item.roleId) {
                  item.roleName = element.roleName
                }
              })
            })
            // 通过部门id 获取 部门名称
            let params2 = {
              url: vm.$base.getUrl('getTree')
            }
            let d2Index, d3Index
            vm.$store.dispatch('getForm', params2).then(res => {
              // 如果是超级管理员，清空部门
              if (vm.$route.query.userRole === 1) {
                item.deptName1 = ''
                item.deptName2 = ''
                item.deptName3 = ''
              } else {
                // 获取并更新1级部门名称
                if (vm.$route.query.deptId1) {
                  res.nodes.forEach((element, index) => {
                    if (element.deptId === vm.$route.query.deptId1) {
                      item.deptName1 = element.deptName
                      d2Index = index
                    }
                  })
                } else {
                  item.deptName1 = ''
                }
                // 获取并更新2级部门名称
                if (vm.$route.query.deptId2 && vm.$route.query.deptId2 !== vm.$route.query.deptId1) {
                  res.nodes[d2Index].nodes.forEach((element, index) => {
                    if (element.deptId === vm.$route.query.deptId2) {
                      item.deptName2 = element.deptName
                      d3Index = index
                    }
                  })
                } else {
                  item.deptName2 = ''
                }
                // 获取并更新3级部门名称
                if (vm.$route.query.deptId3 && vm.$route.query.deptId3 !== vm.$route.query.deptId2) {
                  res.nodes[d2Index].nodes[d3Index].nodes.forEach((element, index) => {
                    if (element.deptId === vm.$route.query.deptId3) {
                      item.deptName3 = element.deptName
                    }
                  })
                } else {
                  item.deptName3 = ''
                }
              }
            })
          }
        })
      }
      vm.$store.commit('keepIn', 'userList')
    })
  }
}
</script>
<style scoped>
.el-table {
  width: auto !important;
  text-align: center;
  margin: 10px;
}

.el-table >>> th {
  text-align: center;
}

.department-top-btn {
  float: right;
}

.department-top-btn .btn-default {
  display: inline-block;
  padding: 2px 12px;
  margin-bottom: 0;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.42857143;
  text-align: center;
  cursor: pointer;
  background: none;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-right: 30px;
}
</style>
